package com.wlcb.jpower.chat.message.handler;

import com.wlcb.jpower.chat.builder.TextBuilder;
import com.wlcb.jpower.chat.service.wxuser.WxUserInfoService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 关注事件
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private WxUserInfoService wxUserInfoService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.debug("新关注用户 OPENID: " + wxMessage.getFromUser());
        String appId = context.get("appId").toString();
        try {
            //收集用户信息
            wxUserInfoService.collectUserInfo(appId, wxMessage.getFromUser());
            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.error("该公众号没有获取用户信息权限！appId={}",appId);
            }
        }
        return null;
    }
}
